﻿using UnityEngine;
using UnityEditor;
using System.Collections;
using System.IO;
public class ServerNavMeshGen :Editor
{
    [MenuItem("SGTools/ServerNavMeshGen")]
    public static void GenServerNavMesh() 
    {
        Vector3[] verts;
        int[] Indices;
        NavMesh.Triangulate(out verts, out Indices);
        if (verts == null && Indices == null) 
        {
            Debug.LogError("请先烘焙Unity的NavMesh");
            return;
        }
        GameObject oldNavMesh =  GameObject.Find("__NavMesh__");
        if (oldNavMesh != null) 
        {
            GameObject.DestroyImmediate(oldNavMesh);
        }
       GameObject NavMeshG  = new  GameObject("__NavMesh__");
       MeshRenderer mr =  NavMeshG.AddComponent<MeshRenderer>();
       MeshFilter mf = NavMeshG.AddComponent<MeshFilter>();
       mf.sharedMesh = new Mesh();
       mf.sharedMesh.vertices = verts;
       mf.sharedMesh.SetIndices(Indices, MeshTopology.Triangles, 0);
       mr.material = new Material(Shader.Find("GUI/Text Shader"));
       mr.material.color = new Color(0,0,1,70f/255f);
    }

    [MenuItem("SGTools/ExportNavMeshToObjFile")]
    public static void ExportNavMeshToObjFile() 
    {
        GameObject NavMeshG = GameObject.Find("__NavMesh__");
        Mesh mesh =  NavMeshG.GetComponent<MeshFilter>().sharedMesh;
        GenMesh(mesh.vertices,mesh.GetIndices(0)); 
       
    }
    static void GenMesh(Vector3[] vet3, int[] Inc)
    {
        string GenPath = Application.dataPath+"/"+Application.loadedLevelName+".obj";
        if (File.Exists(GenPath))
        {
            File.Delete(GenPath);
        }
        StreamWriter sw = File.CreateText(GenPath);
        for (int i = 0; i < vet3.Length; i++)
        {
            sw.WriteLine("v " + (vet3[i].x * -1) + " " + vet3[i].y + " " + vet3[i].z);
        }

        for (int i = 0; i < Inc.Length / 3; i++)
        {
            sw.WriteLine("f " + (Inc[i * 3 + 2] + 1).ToString() + " " + (Inc[i * 3 + 1] + 1).ToString() + " " + (Inc[i * 3 + 0] + 1).ToString());
        }
        sw.Write("\n");
        sw.Flush();
        sw.Close();
    }
}
